<template>
  <div class="container app-container">
    <div class="form">
      <el-form :model="form" :rules="rules" ref="form" label-width="150px">
        <div
          class="title"
          style="
            margin: 20px 0 20px 0;
            height: 20px;
            line-height: 20px;
            border-left: 1px solid #ccc;
            text-indent: 15px;
          "
        >
          基本信息
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="船员手机号" prop="mobile">
              <el-input
                v-model="form.mobile"
                placeholder="请输入船员手机号"
                clearable
                maxlength="11"
                show-word-limit
                :readonly="!this.isMobileEdit"
                @blur="!this.isEdit && checkMobile"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div
          class="title"
          style="
            margin: 20px 0 20px 0;
            height: 20px;
            line-height: 20px;
            border-left: 1px solid #ccc;
            text-indent: 15px;
          "
        >
          身份证证信息
        </div>
        <el-row>
          <el-col :span="4">
            <el-form-item label="身份证头像面" prop="idCardFront">
              <image-upload
                :file-size="fileSize"
                :file-type="fileType"
                :limit="1"
                :value="form.idCardFront"
                tip=""
                @input="handleIdCardFront"
              ></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="身份证国徽面" prop="idCardBack">
              <image-upload
                :file-size="fileSize"
                :file-type="fileType"
                :limit="1"
                :value="form.idCardBack"
                tip=""
                @input="handleIdCardBack"
              ></image-upload>
            </el-form-item>
          </el-col>
          <el-col
            :span="6"
            style="margin-left: 50px; color: #8c939d; font-size: xx-small; line-height: 200%"
          >
            <div>
              <span>上传：身份证照，照片或扫描件。</span>
            </div>
            <div>
              <span>信息需清晰可见，内容真实有效，不得做任何修改。</span>
            </div>
            <div>
              <span>支持 JPG、JPEG、PNG、BMP 格式，大小不超过 5 MB。</span>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="船员姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入船员姓名" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="船员身份证号" prop="idCard">
              <el-input
                v-model="form.idCard"
                placeholder="请输入船员身份证号"
                clearable
                maxlength="18"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="身份证有效期" prop="idCardDate">
              <el-date-picker
                v-model="form.idCardDate"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="截止日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="身份证地址" prop="idCardAddress">
              <el-input
                v-model="form.idCardAddress"
                placeholder="请输入身份证地址"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发证机关名称" prop="idCardIssue">
              <el-input
                v-model="form.idCardIssue"
                placeholder="请输入发证机关名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div
          class="title"
          style="
            margin: 20px 0 20px 0;
            height: 20px;
            line-height: 20px;
            border-left: 1px solid #ccc;
            text-indent: 15px;
          "
        >
          船员适任证
        </div>
        <el-row>
          <el-col :span="4">
            <el-form-item label="船员适任证" prop="credentialsImg">
              <image-upload
                :file-size="fileSize"
                :file-type="fileType"
                :limit="1"
                :value="form.credentialsImg"
                tip=""
                @input="handleCredentialsImg"
              ></image-upload>
            </el-form-item>
          </el-col>
          <el-col
            :span="6"
            style="margin-left: 50px; color: #8c939d; font-size: xx-small; line-height: 200%"
          >
            <div>
              <span>上传：船员适任证，照片或扫描件。</span>
            </div>
            <div>
              <span>信息需清晰可见，内容真实有效，不得做任何修改。</span>
            </div>
            <div>
              <span>支持 JPG、JPEG、PNG、BMP 格式，大小不超过 5 MB。</span>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="持证人姓名" prop="credentialsName">
              <el-input
                v-model="form.credentialsName"
                placeholder="请输入持证人姓名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="职务资格类别" prop="credentialsType">
              <el-select
                v-model="form.credentialsType"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in credentialsTypeList"
                  :key="item.code"
                  :label="item.info"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="证书等级" prop="credentialsLevel">
              <el-select
                v-model="form.credentialsLevel"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in credentialsLevelList"
                  :key="item.code"
                  :label="item.info"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="footer">
      <el-button type="primary" class="submit-btn" @click="submitForm">
        {{ isEdit ? '确定保存' : '确定新增' }}
      </el-button>
    </div>
  </div>
</template>

<script>
// 导入接口方法
import { credentialsTypeEnum, credentialsLevelEnum, idCardOcr } from '@/api/common';
import { add, update, getDetail, checkAuth } from '@/api/crew';

export default {
  name: 'CrewSave',
  components: {},
  data() {
    return {
      // 标题
      title: '',
      // 初始化 id 为 null
      id: null,
      // 初始化 isEdit 为 false
      isEdit: false,
      isMobileEdit: true,
      // 表单参数
      form: {
        id: null, // id
        mobile: null, // 手机号
        idCardFront: null, // 身份证正面（人像面）
        idCardBack: null, // 身份证正面(国徽面)
        name: null, // 姓名
        idCard: null, // 身份证号
        idCardAddress: null, // 身份证地址
        idCardIssue: null, // 发证机关名称
        idCardDate: null,
        idCardBegin: null, // 证件有效期开始时间
        idCardEnd: null, // 证件有效期结束时间
        credentialsImg: null, // 船员适任证照片
        credentialsName: null, // 船员适任证名称
        credentialsType: null, // 证件类型
        credentialsLevel: null, // 证件等级
        createType: 1, // 创建类型
      },
      // 图片显示个数
      limit: 1,
      // 图片大小单位M
      fileSize: 5,
      // 图片类型
      fileType: ['jpg', 'jpeg', 'png', 'bmp'],
      // 证书类型下拉列表
      credentialsTypeList: [],
      // 证书等级下拉列表
      credentialsLevelList: [],
      // 表单校验
      rules: {
        mobile: [{ required: true, message: '船员手机号不能为空', trigger: 'blur' }],
        idCardFront: [{ required: true, message: '请上传身份证人像面', trigger: 'blur' }],
        idCardBack: [{ required: true, message: '请上传身份证国徽面', trigger: 'blur' }],
        name: [{ required: true, message: '船员姓名不能为空', trigger: 'blur' }],
        idCard: [{ required: true, message: '船员身份证号不能为空', trigger: 'blur' }],
        idCardBegin: [{ required: true, message: '身份证有效期开始时间不能为空', trigger: 'blur' }],
        idCardEnd: [{ required: true, message: '身份证有效期结束时间不能为空', trigger: 'blur' }],
        idCardAddress: [{ required: true, message: '身份证地址不能为空', trigger: 'blur' }],
        idCardIssue: [{ required: true, message: '发证机关名称不能为空', trigger: 'blur' }],
        credentialsImg: [{ required: true, message: '请上传船员适任证照片', trigger: 'blur' }],
        credentialsName: [{ required: true, message: '持证人姓名不能为空', trigger: 'blur' }],
        credentialsType: [{ required: true, message: '证件类型不能为空', trigger: 'blur' }],
        credentialsLevel: [{ required: true, message: '证件等级不能为空', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 通过 $route.params 获取路由参数
    this.id = this.$route.query.id ? this.$route.query.id : null;
    this.form.mobile = this.$route.query.mobile ? this.$route.query.mobile : null;
    if (this.form.mobile !== null) {
      this.isMobileEdit = false;
    }
    // 判断是否存在 id 参数
    this.isEdit = !!this.id;
    if (this.isEdit) {
      this.isMobileEdit = false;
      this.getDataById(this.id);
    }
  },
  watch: {
    '$route.query.id': {
      handler(newId, oldId) {
        this.id = newId || null;
        this.isEdit = !!newId;
        if (this.isEdit) {
          this.getDataById(this.id);
        }
      },
      immediate: true, // 在组件创建时立刻执行一次
    },
  },
  mounted() {
    this.getCredentialsTypeList();
    this.getCredentialsLevelList();
  },
  methods: {
    checkMobile() {
      if (!this.form.mobile) {
        this.$message.error('请输入船员手机号');
        return;
      }
      setTimeout(() => {
        // 调后端接口查询手机号是否存在
        checkAuth(this.form.mobile).then((res) => {
          if (res.data) {
            this.$message.error('当前船员已认证，无需重复认证');
            return;
          }
        });
      }, 1000);
    },
    // 证书等级下拉列表
    getCredentialsLevelList() {
      credentialsLevelEnum().then((res) => {
        this.credentialsLevelList = res.data;
      });
    },

    // 获取职务资格下拉列表
    getCredentialsTypeList() {
      credentialsTypeEnum().then((res) => {
        this.credentialsTypeList = res.data;
      });
    },
    // 身份证正面(人像）
    handleIdCardFront(value) {
      this.form.idCardFront = value;
      if (value !== '') {
        idCardOcr(value, 'front').then((res) => {
          this.form.name = res.data.name;
          this.form.idCard = res.data.number;
          this.form.idCardAddress = res.data.address;
        });
      }
    },
    // 身份证反面(国徽面)
    handleIdCardBack(value) {
      this.form.idCardBack = value;
      if (value !== '') {
        idCardOcr(value, 'back').then((res) => {
          this.form.idCardDate = [res.data.validFrom, res.data.validTo];
          this.form.idCardBegin = res.data.validFrom;
          this.form.idCardEnd = res.data.validTo;
          this.form.idCardIssue = res.data.issue;
        });
      }
    },
    // 船员适任证照片
    handleCredentialsImg(value) {
      this.form.credentialsImg = value;
    },
    /** 获取form表单数据 */
    async getDataById(id) {
      getDetail(id).then((res) => {
        this.form = res.data;
        this.form.idCardDate = [res.data.idCardBegin, res.data.idCardEnd];
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.id != null) {
            this.$confirm('确定修改当前内容', '确定保存', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用修改接口
                this.handleUpdate();
              })
              .catch(() => {});
          } else {
            this.$confirm('确定新增', '确定新增', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用新增接口
                this.handleAdd();
              })
              .catch(() => {});
          }
        }
      });
    },

    /** 新增 */
    handleAdd() {
      let saveData = {
        ...this.form,
      };
      saveData.idCardBegin = saveData.idCardDate[0];
      saveData.idCardEnd = saveData.idCardDate[1];
      this.$modal.loading('正在保存...');

      add(saveData)
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess('新增成功');
            this.close();
          } else {
            this.$message.error(res.message);
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 更新 */
    handleUpdate() {
      let saveData = {
        ...this.form,
      };
      saveData.id = this.id;
      saveData.idCardBegin = saveData.idCardDate[0];
      saveData.idCardEnd = saveData.idCardDate[1];
      this.$modal.loading('正在保存...');

      update(saveData)
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess('保存成功');
            this.close();
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 关闭按钮 */
    close() {
      // 跳转地址 和 携带参数
      const obj = {
        path: '/platform/crew/list/index',
      };
      this.$tab.closeOpenPage(obj).then(() => {
        this.$tab.refreshPage(obj);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
}

.submit-btn {
  position: fixed;
  bottom: 10px;
  left: 50%;
}
</style>
